home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 119 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  69 lines

  1. Newsgroups: comp.lang.c
  2. Path: news.kei.com!wang!news
  3. From: emild@cs.technion.ac.il (Kohn Emil Dan)
  4. Subject: Re: Reclaiming memory allocated recursively 
  5. Organization: Technion, Israel Institute of Technology
  6. Date: Tue, 2 Jan 1996 18:23:47 GMT
  7. Message-ID: <Pine.SV4.3.91-heb-2.04.960102200600.6304B-100000@cs.technion.ac.il>
  8. References: <4c8f8q$ln9@yarrow.wt.com.au> 
  9. Sender: news@wang.com
  10.  
  11.  
  12.  
  13. On Tue, 2 Jan 1996, bruce varley wrote:
  14.  
  15. > I'm using self-referential structures as described in K&R 6.5 (page
  16. > 130 in my version). The program runs 'forever',  storing data in a
  17. > binary tree - a days worh of data is collected, then dumped, and the
  18. > whole process starts all over again. My question is:  How can I
  19. > reclaim the memory that has been recursively allocated?  Using the
  20. > same approach as creating the tree  - ie..........
  21. >     struct node *freetree (struct node *p)  
  22. >             {
  23. >             if (p != NULL)  
  24. >                 {
  25. >                 freetree (p -> left)   ;
  26. >                 free (p -> data_pointer) ;
  27. >                 freetree (p -> right)  ;
  28. >                 }
  29. >             return (0)  ;
  30. >             }
  31. > seems unlikely to work, because the memory required to navigate
  32. > through the tree is being deallocated as the process proceeds. In
  33. > fact, the system crashes when I run the routine.
  34. > Any assistance would be most appreciated.
  35. > bvarley@yarrow.wt.com.au    
  36.  
  37. Try this out:
  38.  
  39. void freetree(struct node *p)
  40. {
  41.  
  42. if(p!=NULL)
  43.    {
  44.       freetree(p -> left);
  45.       free(p -> data_pointer);
  46.       freetree(p -> right);
  47.       free(p); /* You have to free the memory allocated to the node, too*/
  48.                /* this seems to be the main problem with your code*/
  49.    }
  50. }
  51. In order to reclaim the memory used by the tree, call freetree, with the 
  52. root of your tree as a parameter.
  53.  
  54. Don't forget to assign NULL to the root of the tree, after the call to 
  55. freetree, otherwise, subsequent calls to the tree insertion function will 
  56. cause your program to crash.
  57.  
  58.  
  59. Hope this helps.
  60.  
  61.                     Best regards, 
  62.  
  63.                                 Emil
  64.